//
//  RangeView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/11/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import UIKit
import SnapKit



final class RangeView: UIView {
    
    private lazy var fromTF: PaddingTextField = {
        let tf = PaddingTextField()
        tf.keyboardType = .numberPad
        tf.backgroundColor = .whiteBlueColor
        tf.layer.cornerRadius = 5
        tf.delegate = self
        return tf
    }()
    private lazy var toTF: PaddingTextField = {
        let tf = PaddingTextField()
        tf.keyboardType = .numberPad
        tf.backgroundColor = .whiteBlueColor
        tf.layer.cornerRadius = 5
        tf.delegate = self
        return tf
    }()
    private lazy var rowStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fillEqually
        stack.spacing = 16.0
        return stack
    }()
    private lazy var slider = RangeSlider(frame: .zero)
    
    // MARK: - Props

    private var min: Int = 0
    private var max: Int = 0
    
    
    private var lowerPrice: Int = 0 {
        didSet {
            fromTF.text = "\(lowerPrice)"
            if lowerPrice == min {
                fromTF.textColor = .greyColor
            } else {
                fromTF.textColor = .black
            }
        }
    }
    
    private var upperPrice: Int = 0 {
        didSet {
            toTF.text = "\(upperPrice)"
            if upperPrice == max {
                toTF.alpha = 0.8
            } else {
                toTF.alpha = 1.0
            }
        }
    }
    
    
    init () {
        super.init(frame: .zero)
        self.addViews()
        slider.addTarget(self, action: #selector(sliderChanged(_:)), for: .valueChanged)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func getLower() -> Int {
        return lowerPrice
    }
    public func getUpper() -> Int {
        return upperPrice
    }
    
    public func setMaxMin (max: Int, min: Int) {
        self.slider.lowerValue = Double(min)
        self.slider.upperValue = Double(max)
        self.lowerPrice = min
        self.upperPrice = max
        self.min = min
        self.max = max
    }
    
    public func setPlaceholder (fromText: String, toText: String) {
        self.fromTF.placeholder = fromText
        self.toTF.placeholder = toText
    }
    
    @objc private func sliderChanged (_ rangeSlider: RangeSlider) {
        self.convertValue(rangeSlider.lowerValue, rangeSlider.upperValue)
    }
    
    private func convertValue (_ upper: Double, _ lower: Double) {
        let total = max - min
        let minPlus = Int((upper - Double(min)) * Double(total))
        let maxPlus = Int((lower - Double(min)) * Double(total))
        
        lowerPrice = min + minPlus
        upperPrice = min + maxPlus
    }
    
    private func convertValue (_ value: Double) -> Double {
        let total = max - min
        let difference = value - Double(min)
        return difference / Double(total) + Double(min)
    }
    
    /*
     value - min = difference
     
     
    */
    
    
}

extension RangeView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == fromTF {
            print(textField.text)
            if let intValue = Int((textField.text ?? "") + string) {
                slider.lowerValue = self.convertValue(Double(intValue))
                lowerPrice = intValue
                
                return string == ""
            } else {
                return true
            }
        } else if textField == toTF {
            if let intValue = Int((textField.text ?? "") + string) {
                slider.upperValue = self.convertValue(Double(intValue))
                upperPrice = intValue
                return string == ""
            } else {
                return true
            }
        } else {
            return true
        }
    }
}


extension RangeView {
    private func addViews () {
        self.addSubview(rowStack)
        self.addSubview(slider)
        rowStack.addArrangedSubview(fromTF)
        rowStack.addArrangedSubview(toTF)
        self.addConstraints()
    }
    private func addConstraints () {
        rowStack.snp.makeConstraints { (make) in
            make.height.equalTo(44)
            make.leading.trailing.top.equalToSuperview()
        }
        slider.snp.makeConstraints { (make) in
            make.top.equalTo(rowStack.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(30.0)
        }
    }
}


